using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using AutoGear.BLL;
using ECommerce.Library.DataStructure;
using ECommerce.Library;
using System.Collections.Generic;

public partial class admin_news_list : SiteAdminBasePage
{
    private int _pageSize = 0;
    private int _totalItem = 0;
    private int _currentPageIndex = 0;
    private int _totalPage = 0;
    private bool _isLastPage = false;
    private bool _isFirstPage = false;
    private string _searchNewsName = string.Empty;
    private string _sortBy = string.Empty;
    private bool _showAllPage = false;
    private bool _useSearch = false;

    protected void Page_Load(object sender, EventArgs e)
    {
        uccResponseMessage.Visible = false;

        if (!IsPostBack)
        {
            this._currentPageIndex = 1;
            LoadData();
            InitControls();

        }
    }


    private void InitControls()
    {
        imbRemove.Attributes.Add("onclick", "javascript:return confirm('Are you sure that you want to delete these items?')");
    }

    private void ReadPagingData()
    {
        this._pageSize = Convert.ToInt32(ViewState["Page_Size"]);
        this._totalItem = Convert.ToInt32(ViewState["Total_Item"]);
        this._currentPageIndex = Convert.ToInt32(ViewState["Current_Page_Index"]);
        this._totalPage = Convert.ToInt32(ViewState["Total_Page"]);
        this._isLastPage = Convert.ToBoolean(ViewState["Is_Last_Page"]);
        this._isFirstPage = Convert.ToBoolean(ViewState["Is_First_Page"]);
        this._searchNewsName = Convert.ToString(ViewState["Search_News_Name"]);
        this._sortBy = Convert.ToString(ViewState["Sort_By"]);
        this._showAllPage = Convert.ToBoolean(ViewState["Show_All_Page"]);
        this._useSearch = Convert.ToBoolean(ViewState["Use_Search"]);
    }

    private void WritePagingData()
    {
        ViewState["Page_Size"] = this._pageSize;
        ViewState["Total_Item"] = this._totalItem;
        ViewState["Current_Page_Index"] = this._currentPageIndex;
        ViewState["Total_Page"] = this._totalPage;
        ViewState["Is_Last_Page"] = this._isLastPage;
        ViewState["Is_First_Page"] = this._isFirstPage;
        ViewState["Search_News_Name"] = this._searchNewsName;
        ViewState["Sort_By"] = this._sortBy;
        ViewState["Show_All_Page"] = this._showAllPage;
        ViewState["Use_Search"] = this._useSearch;
    }

    private ReadWriteCustomCollection<News> FetchData()
    {
        const int SHOW_ALL_COUNT = 999999;
        ReadWriteCustomCollection<News> data = null;
        int firstItem = (this._currentPageIndex - 1) * this._pageSize;
        int pageSize = this._showAllPage ? SHOW_ALL_COUNT : this._pageSize;

        if (this._useSearch && !string.IsNullOrEmpty(this._searchNewsName))
        {
            data = News.GetBackendNewsListByNewsName(this._searchNewsName, false, this._sortBy, firstItem, pageSize);
        }
        else
        {
            data = News.GetBackendNewsList(false, this._sortBy, firstItem, pageSize);
        }
        return data;
    }

    private int GetTotalItemCount()
    {
        int totalItemCount;
        if (this._useSearch && !string.IsNullOrEmpty(this._searchNewsName))
        {
            totalItemCount = News.GetBackendNewsListByNewsNameCount(this._searchNewsName, false);
        }
        else
        {
            totalItemCount = News.GetBackendNewsListCount(false);
        }
        return totalItemCount;
    }

    private void BindGrid()
    {
        ReadPagingData();

        ReadWriteCustomCollection<News> news = FetchData();

        int firstItemPosition = (this._currentPageIndex - 1) * this._pageSize;
        int lastItemPosition = this._currentPageIndex * this._pageSize - 1;

        this._totalItem = GetTotalItemCount();
        this._totalPage = (int)Math.Ceiling(this._totalItem / (double)this._pageSize);

        if (this._showAllPage || lastItemPosition >= this._totalItem)
            lastItemPosition = this._totalItem - 1;

        grvNews.DataSource = news;
        grvNews.DataBind();

        lblFirstItemNumber.Text = this._totalItem == 0 ? "0" : (firstItemPosition + 1).ToString();
        lblLastItemNumber.Text = (lastItemPosition + 1).ToString();
        lblTotalItem.Text = this._totalItem.ToString();

        BindPager();
    }

    private void LoadData()
    {
        this._pageSize = SiteUtility.GridDefaultPageSize;
        this._totalItem = News.GetBackendNewsListCount(false);
        this._currentPageIndex = 1;
        this._totalPage = (int)Math.Ceiling(this._totalItem / (double)this._pageSize);
        this._isLastPage = TestLastPage();
        this._isFirstPage = TestFirstPage();
        this._searchNewsName = string.Empty;
        this._sortBy = "NewsName";
        this._showAllPage = false;
        this._useSearch = false;

        WritePagingData();
        BindGrid();
    }

    protected void Paging_Command(object sender, CommandEventArgs e)
    {
        if (e.CommandName == "paging")
        {
            ReadPagingData();

            if (Convert.ToString(e.CommandArgument) == "All")
            {
                this._currentPageIndex = 1;
                this._showAllPage = true;
            }
            else
            {
                int currentPage = Convert.ToInt32(e.CommandArgument);
                this._currentPageIndex = currentPage;
                this._showAllPage = false;
            }
            grvNews.EditIndex = -1;
            WritePagingData();
            BindGrid();
        }
    }

    protected void Grid_Sort(object sender, CommandEventArgs e)
    {
        if (e.CommandName == "sort")
        {
            grvNews.EditIndex = -1;
            ReadPagingData();
            this._sortBy = (string)e.CommandArgument;
            if (this._sortBy.Contains("DisplayOrder"))
            {
                this._sortBy = this._sortBy.Replace("DisplayOrder", "CONVERT(int,DisplayOrder)");
            }
            WritePagingData();
            BindGrid();
        }
    }

    protected void Grid_Edit(object sender, CommandEventArgs e)
    {
        if (e.CommandName == "edit")
        {
            NavigateToEditPage(sender, e);
        }
    }

    //protected void Grid_Save(object sender, CommandEventArgs e)
    //{
    //    try
    //    {
    //        if (e.CommandName == "save")
    //        {

    //            int categoryId = 0;
    //            int.TryParse((string)e.CommandArgument, out categoryId);
    //            int rowIndex = FindDataIndex((string)e.CommandArgument);

    //            TextBox tbxEditCategoryName = (TextBox)grvCategory.Rows[rowIndex].FindControl("tbxEditCategoryName");
    //            TextBox tbxEditDisplayOrder = (TextBox)grvCategory.Rows[rowIndex].FindControl("tbxEditDisplayOrder");
    //            CheckBox cbxIsActive = (CheckBox)grvCategory.Rows[rowIndex].FindControl("cbxIsActive");
    //            FileUpload fluEditImage = (FileUpload)grvCategory.Rows[rowIndex].FindControl("fluEditImage");

    //            if (categoryId > 0 && !string.IsNullOrEmpty(tbxEditCategoryName.Text))
    //            {
    //                ProductCategory category = ProductCategory.Load(categoryId);
    //                if (category.CategoryName != tbxEditCategoryName.Text)
    //                {
    //                    category.CategoryName = tbxEditCategoryName.Text;
    //                    category.CategoryNameChanged = true;
    //                }
    //                if (fluEditImage.HasFile)
    //                {
    //                    string logoImageFile = SiteUtility.TempFolder + fluEditImage.FileName;
    //                    if (File.Exists(MapPath(logoImageFile)))
    //                        FileAccessUtility.DeleteFile(logoImageFile);

    //                    string logoContentType = fluEditImage.PostedFile.ContentType.ToLower();
    //                    if (logoContentType == "image/jpg" || logoContentType == "image/gif" || logoContentType == "image/png"
    //                        || logoContentType == "image/jpeg" || logoContentType == "image/bmp" || logoContentType == "image/pjpeg"
    //                        || logoContentType == "image/x-png")
    //                    {
    //                        fluEditImage.SaveAs(MapPath(logoImageFile));
    //                        category.CategoryImageUrl = ProductCategory.ChangeCategoryImage(logoImageFile, category);
    //                    }
    //                }
    //                category.DisplayOrder = tbxEditDisplayOrder.Text;
    //                category.IsActive = cbxIsActive.Checked;
    //                category.Update();
    //                uccResponseMessage.SetSuccessMessage("Information is saved successfuly");
    //            }
    //            else
    //                uccResponseMessage.SetFailMessage("There was a problem in saving the information, please try again");

    //            grvCategory.EditIndex = -1;
    //            BindGrid();
    //        }
    //    }
    //    catch (Exception ex)
    //    {
    //        uccResponseMessage.SetFailMessage("There was a problem in saving the information, please try again");
    //    }
    //}

    //protected void Grid_Cancel(object sender, CommandEventArgs e)
    //{
    //    if (e.CommandName == "cancel")
    //    {
    //        grvCategory.EditIndex = -1;
    //        BindGrid();
    //    }
    //}


    protected void News_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.Header)
        {
            CheckBox cbxSelectAll = (CheckBox)e.Row.FindControl("cbxSelectAll");
            cbxSelectAll.Attributes.Add("onclick", "javascript:SelectAll('" + grvNews.ClientID + "','" + cbxSelectAll.ClientID + "','cbxSelect')");
        }

    }

    protected void NavigateToEditPage(object sender, CommandEventArgs e)
    {
        Response.Redirect(CustomSiteMap.NewsEdit + "?nid=" + e.CommandArgument);
    }

    protected void Delete_Items(object sender, ImageClickEventArgs e)
    {
        try
        {
            ReadPagingData();

            ReadWriteCustomCollection<News> news = new ReadWriteCustomCollection<News>();
            foreach (GridViewRow row in grvNews.Rows)
            {
                if (row.RowType == DataControlRowType.DataRow)
                {
                    CheckBox cbxSelect = (CheckBox)row.FindControl("cbxSelect");
                    if (cbxSelect != null && cbxSelect.Checked)
                    {
                        HiddenField hdfNewsId = (HiddenField)row.FindControl("hdfNewsId");
                        news.Add(News.Load(Convert.ToInt32(hdfNewsId.Value)));
                    }
                }
            }
            News.DeleteNews(news);
            LoadData();
            BindGrid();
        }
        catch (Exception ex)
        {
            uccResponseMessage.SetFailMessage("There was a problem in deleting the manufacturer, please try again");
        }
    }

    protected void Search_Click(object sender, ImageClickEventArgs e)
    {
        ReadPagingData();
        this._searchNewsName = Security.BindStringInput(tbxSearchByName.Text, SecurityLevel.Two);
        this._useSearch = string.IsNullOrEmpty(this._searchNewsName) ? false : true;
        WritePagingData();
        BindGrid();
    }

    private void BindPager()
    {
        List<string> pages = new List<string>();
        for (int i = 1; i <= this._totalPage; i++)
            pages.Add(i.ToString());

        rptPaging.DataSource = pages;
        rptPaging.DataBind();
    }

    private bool TestFirstPage()
    {
        if (this._currentPageIndex == 1)
            return true;
        else
            return false;
    }

    private bool TestLastPage()
    {
        if (this._currentPageIndex == this._totalPage)
            return true;
        else
            return false;
    }

    private int FindDataIndex(string dataId)
    {
        //foreach (GridViewRow row in grvCategory.Rows)
        //{
        //    HiddenField hdfCategoryId = (HiddenField)row.FindControl("hdfCategoryId");
        //    if (hdfCategoryId != null && hdfCategoryId.Value == dataId)
        //    {
        //        return row.RowIndex;
        //    }
        //}
        return -1;
    }
    protected void btnNewsAdd_Click(object sender, EventArgs e)
    {
        Response.Redirect(AutoGear.BLL.CustomSiteMap.NewsAdd);
    }
}
